<template>
  <div class="index">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="6rem" class="demo-ruleForm">
      <el-form-item label="请求方式" prop="method">
        <el-select v-model="ruleForm.method" placeholder="请选择请求方式">
          <el-option
            v-for="item in optionsList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="座右铭" prop="motto">
        <el-input v-model="ruleForm.motto" placeholder="请输入座右铭"></el-input>
      </el-form-item>

      <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
    </el-form>
  </div>
</template>

<script>

import { getRequest, postRequest } from '@/api'

export default {
  name: 'index',
  components: {},
  data () {
    return {
      // 表单
      ruleForm: {
        // 请求方式
        method: undefined,
        // 姓名
        name: '',
        // 座右铭
        motto: ''
      },
      // 规则
      rules: {
        method: [
          { required: true, message: '请选择请求方式', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        motto: [
          { required: true, message: '请输入座右铭', trigger: 'blur' },
        ]
      },
      // 请求方式
      optionsList: [
        {
          value: 0,
          label: 'get'
        },
        {
          value: 1,
          label: 'post'
        }
      ]
    }
  },
  mounted () {
  },
  methods: {
    /**
     * 提交表单
     */
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.method) {
            postRequest(this.ruleForm).then(res => {
              console.log(res)
            })
          } else {
            getRequest(this.ruleForm).then(res => {
              console.log(res)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.index {
  height: 80vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
